package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.base.util.MD5;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.mapper.UserLoginRecordMapper;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.UserLoginRecord;
import com.atguigu.srb.core.pojo.query.UserInfoQuery;
import com.atguigu.srb.core.pojo.vo.LoginVO;
import com.atguigu.srb.core.pojo.vo.RegisterVO;
import com.atguigu.srb.core.pojo.vo.UserInfoVO;
import com.atguigu.srb.core.service.UserInfoService;
import com.atguigu.srb.exception.Assert;
import com.atguigu.srb.result.ResponseEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author fun
 * @since 2021-10-29
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserAccountMapper userAccountMapper;
    @Autowired
    UserLoginRecordMapper userLoginRecordMapper;

    @Override
    public void register(RegisterVO registerVO) {
        //优雅地校验
        String mobile = registerVO.getMobile();
        String code = registerVO.getCode();
        String password = registerVO.getPassword();

        //验证码是否为空
        Assert.isTrue(!StringUtils.isEmpty(code),ResponseEnum.CODE_NULL_ERROR);
        //手机号是否为空
        Assert.isTrue(!StringUtils.isEmpty(mobile), ResponseEnum.MOBILE_NULL_ERROR);
        //手机号是否已注册
        Integer isCount = baseMapper.selectCount(new QueryWrapper<UserInfo>().eq("mobile", mobile));
        Assert.isTrue(isCount<=0,ResponseEnum.MOBILE_EXIST_ERROR);
        //验证码是否正确
        String codeCache = (String)redisTemplate.opsForValue().get("srb:sms:code:"+mobile);
        Assert.isTrue(code.equals(codeCache),ResponseEnum.CODE_ERROR);

        //保存userInfo,生成主键
        UserInfo userInfo = new UserInfo();
        userInfo.setNickName(registerVO.getMobile());
        userInfo.setName(registerVO.getMobile());
        userInfo.setMobile(registerVO.getMobile());
        userInfo.setPassword(MD5.encrypt(registerVO.getPassword()));
        userInfo.setStatus(UserInfo.STATUS_NORMAL); //正常
        userInfo.setUserType(registerVO.getUserType());
        //设置一张静态资源服务器上的头像图片
        userInfo.setHeadImg("https://srb-file.oss-cn-beijing.aliyuncs.com/avatar/07.jpg");
        baseMapper.insert(userInfo);

        //保存userAccount
        Long userId = userInfo.getId();
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccountMapper.insert(userAccount);
    }

    @Override
    public UserInfoVO login(LoginVO loginVO, String ip) {
        String mobile = loginVO.getMobile();
        String password = loginVO.getPassword();
        Integer userType = loginVO.getUserType();
        Assert.notEmpty(mobile,ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(password,ResponseEnum.PASSWORD_NULL_ERROR);

        // 校验参数
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        queryWrapper.eq("user_type",userType);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        //用户不存在
        Assert.notNull(userInfo,ResponseEnum.LOGIN_MOBILE_ERROR);
        //校验密码
        Assert.equals(MD5.encrypt(password),userInfo.getPassword(),ResponseEnum.LOGIN_PASSWORD_ERROR);
        //用户是否被禁用
        Assert.equals(userType,userInfo.getUserType(),ResponseEnum.LOGIN_LOKED_ERROR);

        // 生成token
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getName());
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(userInfo,userInfoVO);
        userInfoVO.setToken(token);

        // 记录用户登录日志
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecord.setIp(ip);
        userLoginRecordMapper.insert(userLoginRecord);
        return userInfoVO;
    }

    @Override
    public Page<UserInfo> listPage(Page pageParam, UserInfoQuery userInfoQuery) {
        String mobile = userInfoQuery.getMobile();
        Integer userType = userInfoQuery.getUserType();
        Integer status = userInfoQuery.getStatus();

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .like(!StringUtils.isEmpty(mobile), "mobile",mobile)
                .eq(null!=userType, "user_type",userType)
                .eq(null!=status, "status",status);
        Page page = baseMapper.selectPage(pageParam, queryWrapper);
        return page;
    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);
        baseMapper.updateById(userInfo);
    }

    @Override
    public Boolean checkMobile(String mobile) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        Integer integer = baseMapper.selectCount(queryWrapper);
        return integer > 0;
    }

    @Override
    public String getBindCodeById(Long benefitUserId) {
        UserInfo userInfo = baseMapper.selectById(benefitUserId);
        return userInfo.getBindCode();
    }
}
